# -*- coding: utf-8 -*-
# Project  : JXC
# FileName : VerifyCodeHandler.py
# Time     : 2020/7/30 15:50
# Author  : Mason101

import os
import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter
from common.ComHandler import get_random_name
from common.RedisHandler import RedisHandler


def getChar():
    return chr(random.randint(65, 90))


def getColor():
    return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))


def getColor2():
    return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))


def verify_code(num=4):
    conn = RedisHandler().conn
    #  *n代表生成几个随机字，与下面生成字符的n对应
    width = 60 * num
    height = 60
    #  生成图片
    image = Image.new('RGB', (width, height), (255, 255, 255))
    # 创建Font对象:
    font_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "static", "font", "Arial.ttf")
    font = ImageFont.truetype(font_path, 36)
    # 创建Draw对象:
    draw = ImageDraw.Draw(image)
    # 填充每个像素:
    for x in range(width):
        for y in range(height):
            draw.point((x, y), fill=getColor())
    # 输出文字:
    char_str = ""
    for t in range(num):
        char = getChar()
        char_str += char
        draw.text((60 * t + 10, 10), char, font=font, fill=getColor2())
    # print(char_str)
    # conn.set(char_str, 1, ex=30)    # 30s的有效期
    # 模糊:
    # image = image.filter(ImageFilter.BLUR)
    base_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "static", "verify_code")
    file_name = get_random_name("jpg")
    image.save(base_dir + "/" + file_name, 'jpeg')
    # image.show()
    return file_name


if __name__ == '__main__':
    verify_code(4)
